package com.quanyan.place.web;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.encrypt.CustomCodec;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.entity.ReqAdminUserVo;
import com.quanyan.place.entity.TbAcRole;
import com.quanyan.place.entity.TbAdminUser;
import com.quanyan.place.entity.TbBizPlace;
import com.quanyan.place.entity.TbBizPlaceAuthUser;
import com.quanyan.place.entity.TbSupplier;
import com.quanyan.place.entity.User;
import com.quanyan.place.entity.UserExtend;
import com.quanyan.place.entity.vo.AdminUserVo;
import com.quanyan.place.entity.vo.ReqUpdateAdminUserPwd;
import com.quanyan.place.service.AdminUserService;
import com.quanyan.place.service.PlaceBaseService;
import com.quanyan.place.service.PlaceInnerService;
import com.quanyan.place.service.SupplierService;
import com.quanyan.place.service.UserService;


/**
 * @author songzj
 * @date 16/4/12-16:43
 */
@RestController
//@RequestMapping("/user")
@RequestMapping("/admin/api/place/user")
public class UserController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserService userService;

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private PlaceInnerService placeInnerService;

    @Autowired
    private PlaceBaseService placeBaseService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private OrderPayService orderPayService;
    
    @Autowired
    private PlaceRedisTemplate placeCache;

    @RequestMapping("/{id}")
    @CustomCodec(includes = {"id","nickName","name"})
    public APIResponse<User> userInfo(@PathVariable("id") int id) {



        logger.warn("access======================>");
        return this.userService.userInfo(id);
    }

    @RequestMapping("/userExtend/{id}")
    public UserExtend userExtend(@PathVariable("id") int id) throws Exception {

        return new UserExtend();
    }

    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    public APIResponse login(
            @RequestParam(value = "loginName", required = true) String loginName,
            @RequestParam(value = "password", required = true) String password) {
        APIResponse result = userService.userLogin(loginName, password);
        if (result.isRet()){
            // TODO 临时方案，把商家用户冗余到场馆管理后台
            TbAdminUser user = (TbAdminUser)result.getData();
            List<TbBizPlaceAuthUser> placeAuthList = placeInnerService.getAuthPlaceForUser(user.getId());
            if (!placeAuthList.isEmpty()){
                TbBizPlaceAuthUser authPlace = placeAuthList.get(0); // 目前只授权给商家前台用。一个前台只隶属于一个场馆
                TbBizPlace place = placeBaseService.getPlaceById(authPlace.getPlaceId());
                user.setChannelId(authPlace.getPlaceId()); // 借用channelId 传递商家 placeId
                if (null != place){
                    user.setAddress("【" + place.getCode() + "】" +place.getName());
                }
            }
            AdminUserVo adminUserVo = new AdminUserVo();
            BeanUtils.copyProperties(user,adminUserVo);
            APIResponse supplierResponse = supplierService.getSupplierListByAdminUid(user.getId());
            if (supplierResponse.isRet()){
                List<TbSupplier> tbSupplierList = (List<TbSupplier>)supplierResponse.getData();
                adminUserVo.setSupplierList(tbSupplierList);

                if (null != tbSupplierList && tbSupplierList.size() > 0){
                    Integer supplierId = tbSupplierList.get(0).getId();
                    if (null != supplierId){
                        List<TbBizPlace> tbBizPlaceList = (List<TbBizPlace>)supplierService.getPlaceListForSupplier(supplierId);
                        if (CollectionUtils.isEmpty(tbBizPlaceList)){
                            return APIResponse.returnFail("该商家旗下未关联任何场馆");
                        }
                        adminUserVo.setPlaceList(tbBizPlaceList);
                    }
                }
            }
            result.setData(adminUserVo);
        }
        
        return result;
//        ModelAndView modelAndView = new ModelAndView("helloIndex");
//        modelAndView.addObject("result",result);
    }


    @RequestMapping(value = "/userRegisterByMobile")
    public APIResponse<?> userRegisterByMobile(@RequestParam("mobile") String mobile) {
        return userService.userRegisterByMobile(mobile);
    }


    /**
     * 增加Server端校验.
     *
     * @RequestBody 接收RequestBody JSON 参数.
     * @Valid 校验该Model的参数有效性.
     */
    @RequestMapping(value = "/regist", method = RequestMethod.POST)
    public APIResponse<?> register(@RequestBody @Valid UserExtend userExtend, BindingResult bindingResult) {
        //冲突测试3
        return APIResponse.returnSuccess();
    }

    /**
     * 获取部门列表
     * @return
     */
    @RequestMapping(value = "/getDeptList")
    public APIResponse getDeptList(@RequestParam(value = "parentId", required = false) Integer parentId){
        return APIResponse.returnSuccess(adminUserService.getDeptList(parentId));
    }

    /**
     * 获取后台用户列表
     * @return
     */
    @RequestMapping(value = "/getAdminUserList")
    public APIResponse<?> getAdminUserList(@RequestBody @Valid ReqAdminUserVo reqAdminUserVo,BindingResult bindingResult){
        Object result = null;
        try {
            result = adminUserService.getAdminUserList(reqAdminUserVo);
            return APIResponse.returnSuccess(result);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return APIResponse.returnFail(e.getMessage());
        }
    }


    /**
     * 增加后端用户
     * @param adminUserVo
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/saveAdminUser", method = RequestMethod.POST)
    public APIResponse saveAdminUser(@RequestBody @Valid AdminUserVo adminUserVo, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        if (adminUserVo.getId() == null) {
        	 if (adminUserService.existsUser(adminUserVo)){
                 return APIResponse.returnFail("登录用户已存在");
             }
		}
        int result = adminUserService.saveAdminUser(adminUserVo);
        if (result > 0){
            return APIResponse.returnSuccess();
        } else {
            return APIResponse.returnFail("保存用户失败");
        }

    }

    /**
     * 密码重置
     * @param adminUserVo
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/updateUserPassword", method = RequestMethod.POST)
    public APIResponse updateUserPassword(@RequestBody @Valid AdminUserVo adminUserVo, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        int result = adminUserService.updateUserPassword(adminUserVo);
        if (result > 0){
            return APIResponse.returnSuccess();
        } else {
            return APIResponse.returnFail("密码重置失败");
        }

    }

    /**
     * 通过Id拿到用户信息
     * @param id
     * @return
     */
    @RequestMapping(value="/getAdminUserById",method = RequestMethod.GET)
    public APIResponse<?> getAdminUserById(@RequestParam (value="id") String id){
        return APIResponse.returnSuccess(adminUserService.getAdminUserById(Integer.parseInt(id)));
    }


    /**
     * 修改密码
     * @param reqUpdateAdminUserPwd
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/updateAdminUserPwd" , method = RequestMethod.POST)
    public APIResponse<?> userPasswordUpdate(@RequestBody @Valid ReqUpdateAdminUserPwd reqUpdateAdminUserPwd, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        return adminUserService.userPasswordUpdate(reqUpdateAdminUserPwd.getUid(), reqUpdateAdminUserPwd.getOldPassword(), reqUpdateAdminUserPwd.getNewPassword(), reqUpdateAdminUserPwd.getRePassword());

    }

    /**
     * 修改密码
     * @param vo
     * @param
     * @return
     */
    @RequestMapping(value = "/updateUserInfo" , method = RequestMethod.POST)
    public APIResponse<?> updateUserInfo(@RequestBody @Valid AdminUserVo vo) {
        adminUserService.updateUserInfo(vo);
        return APIResponse.returnSuccess();
    }

    /**
     * 获取未授权的供应商用户  {groupId = 23}
     * @param map
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/getSupplierUserList" , method = RequestMethod.POST)
    public APIResponse<?> getSupplierUserList(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        Integer pageNum = MapUtils.getInteger(map,"pageNum");
        Integer pageSize = MapUtils.getInteger(map,"pageSize");
        Integer groupId = MapUtils.getInteger(map,"groupId");

        Object result = null;
        try {
            result = adminUserService.getSupplierUserList(pageNum,pageSize,groupId);
            return APIResponse.returnSuccess(result);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return APIResponse.returnFail(e.getMessage());
        }
    }

    @RequestMapping(value = "/getBankList")
    public APIResponse<?> getBankList() {
        APIResponse response = null;
        try{
            response = orderPayService.getBankList();
        }catch (Exception e){
            return APIResponse.returnFail("调用支付系统失败！");
        }
        return response;
    }
    
    /**
     * 获取所有的权限资源 , 树形结构展示
     * @return
     */
    @RequestMapping(value = "/getAllResources")
    public APIResponse<?> getAllResources() {
        try{
           return APIResponse.returnSuccess(adminUserService.getAllResources());
        }catch (Exception e){
           return APIResponse.returnFail("获取所有的权限资源失败！");
        }
    }
    
    
    /**
     * 查询角色
     * @return
     */
    @RequestMapping(value = "/getRoles")
    public APIResponse<?> getAllRoles(TbAcRole tbAcRole) {
        try{
        	return APIResponse.returnSuccess(adminUserService.getRoles(tbAcRole));
        }catch (Exception e){
            logger.error(e.getMessage());
            return APIResponse.returnFail("查询所有角色失败！");
        }
    }
    
    /**
     * 保存或更新角色
     * @return
     */
    @RequestMapping(value = "/saveAdminRole")
    public APIResponse<?> saveAdminRole(@RequestBody @Valid TbAcRole tbAcRole) {
        try{
        	adminUserService.saveAdminRole(tbAcRole);
        	return APIResponse.returnSuccess(ApiResponseEnum.SUCCESS);
        }catch (Exception e){
        	logger.error(e.getMessage());
            return APIResponse.returnFail("保存或更新角色失败！");
        }
    }
    
    
    /**
     * 保存或更新角色资源权限
     * @return
     */
    @RequestMapping(value = "/saveAdminPermission")
    public APIResponse<?> saveAdminPermission(@RequestBody @Valid TbAcRole tbAcRole) {
        try{
        	adminUserService.saveAdminPermission(tbAcRole.getId(), tbAcRole.getResourceIds());
        	return APIResponse.returnSuccess(ApiResponseEnum.SUCCESS);
        }catch (Exception e){
        	logger.error(e.getMessage());
            return APIResponse.returnFail("根据角色查询资源权限失败！");
        }
    }
    
    /**
     * 根据角色查询资源权限 
     * @return
     */
    @RequestMapping(value = "/getResourcesByRoleId", method = RequestMethod.GET)
    public APIResponse<?> getResourcesByRoleId(@RequestParam(value = "roleId") String roleId) {
        try{
        	return APIResponse.returnSuccess(adminUserService.getResourceByRole(Integer.valueOf(roleId)));
        }catch (Exception e){
        	logger.error(e.getMessage());
            return APIResponse.returnFail("根据角色查询资源权限失败！");
        }
    }
    
}
